﻿using System;
using System.Data;
using System.Drawing;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Web.UI;
using System.Collections.Generic;
using System.Globalization;

public partial class PaymentByList : System.Web.UI.Page
{
    ServerObject mServerObject = null;
    string appPath = string.Empty;
    bool showValutaColumns = true;
    static string prevPage = String.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {       
        if (mServerObject == null) mServerObject = new ServerObject();

        if (Utils.AutentificatedUser)
        {
            appPath = Utils.GetApplicationPath(Request);

            if (Request["loanID"] != null)
            {
                if (!IsPostBack)
                {
                    prevPage = "Credits.aspx?cd=" + Request["loanID"];
                    ShowPanel(viewCreditDetailsPanel.ID);
                }
            }            
        }
        else
        {
            ShowPanel(string.Empty);
        }
    }

    private void ShowPanel(string panelName)
    {
        #region Hide panels

        emptyPanel.Visible = false;

        viewCreditDetailsPanel.Visible = false;

        #endregion Hide panels

        try
        {
            #region Get Panel Name

            switch (panelName)
            {
                case "viewCreditDetailsPanel":
                    viewCreditDetailsPanel.Visible = true;

                    FillViewCreditsInfo();

                    FillCalculatedOrdersGridView();
                    break;                    

                default:
                    emptyPanel.Visible = true;
                    break;
            }

            #endregion Get Panel Name
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    private void FillViewCreditsInfo()
    {
        int loanID = 0;
        int.TryParse(Request["loanID"], out loanID);

        Credits.DataObjects.LoanObject loanDetails = Utils.ModuleCredits().GetLoanObjectByID(loanID);
        if (loanDetails != null)
        {
            creditDetContractCodeLabel.Text = loanDetails.ContractCode.ToString();
            creditDetClientDescriptionHyperLink.Text = loanDetails.ClientFirstLastName;
            creditDetClientDescriptionHyperLink.NavigateUrl = appPath + "/ModuleCredits/client.aspx?clid=" + loanDetails.ClientID;
            creditDetLoanStartDateLabel.Text = loanDetails.LoanStartDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
            credtDetLoanEndDateLabel.Text = loanDetails.LoanEndDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
            credtDetFoundingLineLabel.Text = loanDetails.CreditFundingLine;
            creditDetCreditAmountLabel.Text = loanDetails.ContractAmount.ToString();
            creditDetNrOfCreditMonthLabel.Text = loanDetails.NrOfCreditMonth.ToString();
            creditDetPercentValueLabel.Text = loanDetails.ContrcatPercent.ToString();
            creditDetCalculatePercentFromLabel.Text = loanDetails.CalculatePercentFromString.ToString();
            creditDetPenaltyValueLabel.Text = loanDetails.ContractPenalty.ToString();
            creditDetCalclatePEnaltyFromLabel.Text = loanDetails.CalculatePenaltyFromString.ToString();
            creditDetpenaltyGracePeriodLabel.Text = loanDetails.PenaltyGracePeriod.ToString();
            creditDetLoanScopeLabel.Text = loanDetails.LoanScope;
            //creditDetGarantorIDLabel.Text = loanDetails.Rows[0]["garantorDescription"].ToString();
            //creditDetPledgeLabel.Text = loanDetails.Rows[0]["pledge"].ToString();
            creditDetLoanCategoryLabel.Text = loanDetails.LoanCategoryString;
            creditDetLastModificationBYLabel.Text = loanDetails.ModifiedByString;
            initialPeriodLabel.Text = loanDetails.PayPeriodIDString;

            showValutaColumns = loanDetails.CurrencyID != 1;
        }
    }
    
    protected void FillCalculatedOrdersGridView()
    {
        try
        {
            int loanID = 0;
            int.TryParse(Request["loanID"], out loanID);

            DataTable orderList = Utils.ModuleCredits().GetLoanOrderList(loanID);

            if (orderList != null && orderList.Rows.Count > 0)
            {
                Credits.DataObjects.LoanObject loanInfo = Utils.ModuleCredits().GetLoanObjectByID(loanID);

                decimal penaltyValue = loanInfo.ContractPenalty;
                int calculatePenaltyFrom = loanInfo.CalculatePenaltyFrom;
                decimal initialAmount = loanInfo.ContractAmount;

                orderList.Columns.Add("SoldFinal", typeof(decimal));
                orderList.Columns.Add("totalPaymentAmount", typeof(decimal));
                
                orderList.Columns.Add("difDobinda", typeof(decimal));
                orderList.Columns.Add("difMain", typeof(decimal));


                for (int indexRow = 0; indexRow < orderList.Rows.Count; indexRow++)
                {
                    #region Penalitati
                   // bool zeroPayment = false;
                    string orderNumber = string.Empty;
                    orderNumber = orderList.Rows[indexRow]["payedOrderNumber"].ToString();

                    decimal currencyRate = 0;
                    decimal.TryParse(orderList.Rows[indexRow]["currencyChangeRate"].ToString(), out currencyRate);
                    if (currencyRate == 0)
                    {
                        currencyRate = 1;
                    }

                    decimal mainRate = 0;
                    decimal.TryParse(orderList.Rows[indexRow]["mainRate"].ToString(), out mainRate);
                    
                    decimal difDobinda = 0;
                    decimal difMain = 0;

                    decimal percentValue = 0;
                    decimal.TryParse(orderList.Rows[indexRow]["percentValue"].ToString(), out percentValue);

                    if (string.IsNullOrEmpty(orderNumber))
                    {
                    #region
                        decimal penaltyAmount = 0;

                        DateTime calculatedData = (DateTime)orderList.Rows[indexRow]["calculatedData"];

                        int delayDaysCount = (DateTime.Now - calculatedData).Days;

                        switch (calculatePenaltyFrom)
                        {
                            case (int)Constants.Constants.Classifiers.CalculatePenalty_DeLaSumaIntirzierii:
                                {
                                    penaltyAmount = ((percentValue + mainRate) * penaltyValue * currencyRate) / 100 * delayDaysCount;
                                }
                                break;

                            case (int)Constants.Constants.Classifiers.CalculatePenalty_DinSumaInitiala:
                                {
                                    penaltyAmount = (initialAmount * penaltyValue * currencyRate) / 100 * delayDaysCount;
                                }
                                break;

                            case (int)Constants.Constants.Classifiers.CalculatePenalty_SumaFixa:
                                {
                                    penaltyAmount = penaltyValue * delayDaysCount;
                                }
                                break;

                            default:
                                break;
                        }

                        if (penaltyAmount < 0)
                        {
                            //zeroPayment = true;
                            penaltyAmount = 0;
                        }

                        orderList.Rows[indexRow]["additionalPays"] = Math.Round(penaltyAmount,2);

                    #endregion
                    }
                    else
                    {

                        decimal percentValue_Pays = Crypt.Utils.MyDecimalParce(orderList.Rows[indexRow]["percentValue_Pays"].ToString());

                        decimal mainRate_Pays = Crypt.Utils.MyDecimalParce(orderList.Rows[indexRow]["mainRate_Pays"].ToString());

                        difDobinda = (percentValue_Pays - percentValue) * currencyRate;

                        difMain = (mainRate_Pays - mainRate) * currencyRate;
                        
                    }
                    orderList.Rows[indexRow]["difDobinda"] = Math.Round(difDobinda,2);
                    orderList.Rows[indexRow]["difMain"] = Math.Round(difMain,2);
                    #endregion

                    #region SoldFinal
                    string soldInitial = orderList.Rows[indexRow]["remainingAmount"].ToString();
                    decimal soldInitialValue = Crypt.Utils.MyDecimalParce(soldInitial);

                    string rataPrincipal = orderList.Rows[indexRow]["mainRate_Pays"].ToString();
                    decimal rataPrincipalValue = Crypt.Utils.MyDecimalParce(rataPrincipal);

                    orderList.Rows[indexRow]["SoldFinal"] = soldInitialValue - rataPrincipalValue;
                    #endregion

                    #region TotalPaymentAmount
                    //additionalPays+percentValue+mainRate
                    string additionalPays = orderList.Rows[indexRow]["additionalPays"].ToString();
                    decimal additionalPaysValue = Crypt.Utils.MyDecimalParce(additionalPays);

                    string percentPays = orderList.Rows[indexRow]["percentValue_Pays"].ToString();
                    decimal percentValuePays = Crypt.Utils.MyDecimalParce(percentPays);

                    string mainRatePays = orderList.Rows[indexRow]["mainRate_Pays"].ToString();
                    decimal mainRateValue = Crypt.Utils.MyDecimalParce(mainRatePays);

                    orderList.Rows[indexRow]["totalPaymentAmount"] = additionalPaysValue + percentValuePays + mainRateValue;

                    #endregion

                    #region payedDate
                    string payedDate = orderList.Rows[indexRow]["payedDate"].ToString();
                    if (string.IsNullOrEmpty(payedDate))
                    {
                        orderList.Rows[indexRow]["payedDate"] = DateTime.Now; // orderList.Rows[indexRow]["calculatedData"].ToString();
                    }
                    #endregion

                    #region Intirziere
                    //string additionalPaysComment = orderList.Rows[indexRow]["additionalPaysComment"].ToString();
                    //additionalPaysComment = additionalPaysComment.Replace("Intirzierea de ", string.Empty);
                    //additionalPaysComment = additionalPaysComment.Replace(" zile", string.Empty);
                    //orderList.Rows[indexRow]["additionalPaysComment"] = additionalPaysComment;

                    DateTime firstDate = (DateTime)orderList.Rows[indexRow]["calculatedData"];
                    DateTime finalDate = (DateTime)orderList.Rows[indexRow]["payedDate"];
                    double difDate = (finalDate - firstDate).TotalDays;
                    orderList.Rows[indexRow]["additionalPaysComment"] = Convert.ToInt32(difDate);
                    #endregion
                }

                newCalculatedOrdersGridView.DataSource = orderList;

            }
            else
            {
                newCalculatedOrdersGridView.DataSource = null;
            }

            newCalculatedOrdersGridView.DataBind();

            #region show/hide column
            if (showValutaColumns)
            {
                newCalculatedOrdersGridView.Columns[7].HeaderStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[8].HeaderStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[9].HeaderStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[10].HeaderStyle.CssClass = string.Empty;

                newCalculatedOrdersGridView.Columns[7].ItemStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[8].ItemStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[9].ItemStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[10].ItemStyle.CssClass = string.Empty;

                newCalculatedOrdersGridView.Columns[7].FooterStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[8].FooterStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[9].FooterStyle.CssClass = string.Empty;
                newCalculatedOrdersGridView.Columns[10].FooterStyle.CssClass = string.Empty;
            }
            else
            {
                newCalculatedOrdersGridView.Columns[10].ItemStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[7].ItemStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[8].ItemStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[9].ItemStyle.CssClass = "HiddenColumn";

                newCalculatedOrdersGridView.Columns[10].HeaderStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[7].HeaderStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[8].HeaderStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[9].HeaderStyle.CssClass = "HiddenColumn";

                newCalculatedOrdersGridView.Columns[10].FooterStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[7].FooterStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[8].FooterStyle.CssClass = "HiddenColumn";
                newCalculatedOrdersGridView.Columns[9].FooterStyle.CssClass = "HiddenColumn";
            }
            #endregion
 }
        catch (Exception ex)
        {
            string message = ex.Message;
        }
    }

    decimal sumPercentValueLabel = 0;
    decimal sumMainRateLabel = 0;
    decimal sumtotalAmountLabel = 0;
    decimal sumadditionalPays = 0;
    decimal sumprocentPaymentValueTextBoxID = 0;
    decimal sumratePaymentTextBoxID = 0;
    decimal sumtotalPaymentTextBoxID = 0;
    decimal sumdifPaymentTextBoxID = 0;

    private decimal GetTotalForFooter(string nameLabel, GridViewRowEventArgs e, string typeToolBox)
    {        
        decimal result = 0;
        switch (typeToolBox)
        {
            case "Label":
                Label valueLabel = (Label)e.Row.FindControl(nameLabel);
                if (valueLabel != null)
                {
                    result += Crypt.Utils.MyDecimalParce(valueLabel.Text);
                }
                break;
            case"TextBox":
                TextBox valueTextBox = (TextBox)e.Row.FindControl(nameLabel);
                if (valueTextBox != null)
                {
                    result += Crypt.Utils.MyDecimalParce(valueTextBox.Text);
                }
                break;
            default:
                break;
        }
        return result;
    }

    protected void backButton_Click(object sender, EventArgs e)
    {
        Response.Redirect(prevPage);
    }

    protected void newCalculatedOrdersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            sumPercentValueLabel += GetTotalForFooter("percentValueLabel", e, "Label");
            sumMainRateLabel += GetTotalForFooter("mainRateLabel", e, "Label");
            sumtotalAmountLabel += GetTotalForFooter("totalAmountLabel", e, "Label");
            sumadditionalPays += GetTotalForFooter("additionalPays", e, "TextBox");
            sumprocentPaymentValueTextBoxID += GetTotalForFooter("procentPaymentValueTextBoxID", e, "TextBox");
            sumratePaymentTextBoxID += GetTotalForFooter("ratePaymentTextBoxID", e, "TextBox");
            sumtotalPaymentTextBoxID += GetTotalForFooter("totalPaymentTextBoxID", e, "TextBox");
            sumdifPaymentTextBoxID += GetTotalForFooter("difPaymentTextBoxID", e, "TextBox");

            TextBox valueTextBox = (TextBox)e.Row.FindControl("difPaymentTextBoxID");
            if (valueTextBox != null)
            {
                decimal difValue = Crypt.Utils.MyDecimalParce(valueTextBox.Text);
                
                if (difValue > 0)
                {
                    valueTextBox.ForeColor = Color.Green;
                    valueTextBox.Font.Bold = true;
                }
                if (difValue < 0)
                {
                    valueTextBox.ForeColor = Color.Red;
                    valueTextBox.Font.Bold = true;
                }
            }
            Label dayLabel = (Label)e.Row.FindControl("additionalPaysCommentLabel");
            int dayValue = 0;
            int.TryParse(dayLabel.Text.ToString(), out dayValue);
            if (dayValue > 0)
            {
                dayLabel.ForeColor = Color.Red;
                dayLabel.Font.Bold = true;
            }

            Label difDobindaLabel = (Label)e.Row.FindControl("procentPaymentDifLabel");
            decimal difDobinda = Crypt.Utils.MyDecimalParce(difDobindaLabel.Text.ToString());
            if (difDobinda < 0)
            {
                difDobindaLabel.ForeColor = Color.Red;
                difDobindaLabel.Font.Bold = true;
            }
            else
            {
                difDobindaLabel.Text = string.Empty;
            }

            Label difMainLabel = (Label)e.Row.FindControl("ratePaymentDifLabel");
            decimal difMain = Crypt.Utils.MyDecimalParce(difMainLabel.Text.ToString());
            if (difMain < 0)
            {
                difMainLabel.ForeColor = Color.Red;
                difMainLabel.Font.Bold = true;
            }
            else
            {
                difMainLabel.Text = string.Empty;
            }


            Label valueLabel = (Label)e.Row.FindControl("payedOrderNumberLabel");
            string htmlColor = "";
            if (string.IsNullOrEmpty(valueLabel.Text))
            {
                if (e.Row.RowIndex % 2 == 0)
                {
                    htmlColor = "#EBF6FE"; // "#c2c6b3";                   
                }
                else
                {
                    htmlColor = "#CFD4F2";  // "#dad295";
                }
            }
            else
            {
                if (e.Row.RowIndex % 2 == 0)
                {
                    htmlColor = "#FFF8D6"; // "#c2c6b3";                   
                }
                else
                {
                    htmlColor = "#FFF1AE";  // "#dad295";
                }
            }
            e.Row.Cells[11].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
            e.Row.Cells[12].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
            e.Row.Cells[13].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
            e.Row.Cells[14].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
            e.Row.Cells[15].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
            e.Row.Cells[16].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
            e.Row.Cells[17].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
            e.Row.Cells[18].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
            e.Row.Cells[19].BackColor = System.Drawing.ColorTranslator.FromHtml(htmlColor);
        }

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label totalPercentLabel = (Label)e.Row.FindControl("totalPercentLabel");
            totalPercentLabel.Text = sumPercentValueLabel.ToString();

            Label totalMainRateLabel = (Label)e.Row.FindControl("totalMainRateLabel");
            totalMainRateLabel.Text = sumMainRateLabel.ToString();

            Label totalAnuitateLabel = (Label)e.Row.FindControl("totalAnuitateLabel");
            totalAnuitateLabel.Text = sumtotalAmountLabel.ToString();

            Label totalAdditionalPaysLabel = (Label)e.Row.FindControl("totalAdditionalPaysLabel");
            totalAdditionalPaysLabel.Text = sumadditionalPays.ToString();

            Label totalProcentPaymentLabel = (Label)e.Row.FindControl("totalProcentPaymentLabel");
            totalProcentPaymentLabel.Text = sumprocentPaymentValueTextBoxID.ToString();

            Label totalRatePaymentPrincipalaLabel = (Label)e.Row.FindControl("totalRatePaymentPrincipalaLabel");
            totalRatePaymentPrincipalaLabel.Text = sumratePaymentTextBoxID.ToString();

            Label totalTotalPaymentPrincipalaLabel = (Label)e.Row.FindControl("totalTotalPaymentPrincipalaLabel");
            totalTotalPaymentPrincipalaLabel.Text = sumtotalPaymentTextBoxID.ToString();

            Label totalDifPaymentPrincipalaLabel = (Label)e.Row.FindControl("totalDifPaymentPrincipalaLabel");
            totalDifPaymentPrincipalaLabel.Text = sumdifPaymentTextBoxID.ToString();
        }
    }

    protected void newCalculatedOrdersGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            int loanID = 0;
            int.TryParse(Request["loanID"], out loanID);

            if (loanID != 0)
            {
                string hiddenValue = rowHiddenValueID.Value;

                List<string> cellsArray = new List<string>(hiddenValue.Split('|'));
                //Update the values.
                GridViewRow row = newCalculatedOrdersGridView.Rows[e.RowIndex];

                int iterationID = 0;
                int.TryParse(row.Cells[0].Text, out iterationID);

                #region cursMDL
                TextBox cursMDLTextBox = (TextBox)(row.Cells[7].FindControl("currencyChangeRateInputID"));
                decimal cursMDL = Crypt.Utils.MyDecimalParce(cursMDLTextBox.Text);
                #endregion cursMDL

                #region calcData
                TextBox calcDataTextBox = (TextBox)(row.Cells[11].FindControl("payedDateTextBoxID"));
                DateTime calculatedData = Crypt.Utils.ToDateTime(calcDataTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);
                #endregion

                #region percent
                decimal percentValue = Crypt.Utils.MyDecimalParce(cellsArray[1]);
                #endregion

                #region mainRate
                decimal mainRate = Crypt.Utils.MyDecimalParce(cellsArray[2]);
                #endregion

                #region remaining
                Label remainingLabel = (Label)(row.Cells[2].FindControl("remainingAmountLabel"));
                decimal remainingAmount = Crypt.Utils.MyDecimalParce(remainingLabel.Text);
                #endregion

                #region penality
                decimal penaltyAmount = Crypt.Utils.MyDecimalParce(cellsArray[0]);
                #endregion

                #region insertPays
                decimal insertPays = 0;
                TextBox insertPaysTextBox = (TextBox)(row.Cells[13].FindControl("incassaPays"));
                insertPays = Crypt.Utils.MyDecimalParce(insertPaysTextBox.Text);
                #endregion insertPays

                #region difPayment
                decimal difPayment = Crypt.Utils.MyDecimalParce(cellsArray[4]);
                #endregion difPayment

                string penaltyComment = cellsArray[3];

                bool result = Utils.ModuleCredits().UpdateLoanOrderPays(loanID, iterationID-1, calculatedData, percentValue, mainRate, remainingAmount, penaltyAmount, penaltyComment, insertPays, difPayment, cursMDL);
                if (result)
                {
                    int nextIteration = iterationID;
                    string payedOrderNumber = loanID.ToString() + "_" + nextIteration.ToString();
                    Utils.ModuleCredits().UpdateLoanOrder(loanID, iterationID-1, calculatedData, payedOrderNumber);
                    
                    //Reset the edit index.
                    newCalculatedOrdersGridView.EditIndex = -1;
                    
                    ShowPanel(viewCreditDetailsPanel.ID);
                    rowHiddenValueID.Value = string.Empty;
                }
                else
                {
                    Utils.InfoText(this, "Atentie!", "In procesul salvarii au aparut errori. Salvarea a fost executata partial sau nu au fost salvata deloc! Incercati mai tirziu!");
                }
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    protected void newCalculatedOrdersGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {        
        try
        {
            int loanID = 0;
            int.TryParse(Request["loanID"], out loanID);

            if (loanID != 0)
            {
                //Update the values.
                GridViewRow row = newCalculatedOrdersGridView.Rows[e.RowIndex];

                DataTable dt = (DataTable)newCalculatedOrdersGridView.DataSource;

                int iterationID = 0;
                int.TryParse(row.Cells[0].Text, out iterationID);

                if (mServerObject.DeletePaymentByList(loanID, iterationID))
                {
                    ShowPanel(viewCreditDetailsPanel.ID);
                }
                else
                {
                    Utils.InfoText(this, "Atentie", " Stergerea bancii nu a fost efectuata. Verificati conectiunea internetului ");
                }
            }
        }
        catch (Exception ex)
        { Utils.InfoText(this, "Eroare in System!", ex.Message.ToString()); }
    }

}






